package com.vortex.cloud.zhsw.xinyang.util;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.vortex.cloud.vfs.common.exception.VortexException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;


public class ExcelHelper {

    public static <T> List<T> getInputList(InputStream inputStream, Class<T> tClass, Integer titleRows,
                                           Integer headRow) throws Exception {
        ImportParams params = new ImportParams();
        //导入数据的时候排除标题行
        params.setTitleRows(titleRows);
        //导入数据的时候排除表头行
        params.setHeadRows(headRow);
        return ExcelImportUtil.importExcel(inputStream, tClass, params);
    }

    public static <T> List<T> getInputList(InputStream inputStream, Class<T> tClass, Integer titleRows,
                                           Integer headRow,Integer sheetNum) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headRow);
        params.setSheetNum(sheetNum);
        return ExcelImportUtil.importExcel(inputStream, tClass, params);
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new VortexException("excel文件不能为空");
        } catch (Exception e) {
            throw new VortexException(e.getMessage());
        }
        return list;
    }

    /**
     * @param inputStream      excel输入流
     * @param titleRow         标题行数
     * @param headRow          头行数
     * @param lastOfInvalidRow 忽略最后几行
     * @Description 导入excel到List<Map> 集合中
     **/
    public static List<Map<String, String>> importExcel(InputStream inputStream, int titleRow, int headRow, int lastOfInvalidRow) throws Exception {
        ImportParams params = new ImportParams();
        params.setLastOfInvalidRow(lastOfInvalidRow);
        params.setTitleRows(titleRow);
        params.setHeadRows(headRow);
        return ExcelImportUtil.importExcel(inputStream, Map.class, params);
    }

    /**
     * @param inputStream      excel输入流
     * @param startRowIndex    开始行号
     * @param lastOfInvalidRow 忽略最后几行
     * @Description
     **/
    public static List<List<Object>> importExcel(InputStream inputStream, int startRowIndex, int lastOfInvalidRow) {
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<List<Object>> read = reader.read(startRowIndex);
        return read.subList(0, read.size() - lastOfInvalidRow);
    }

    /**
     * @param response  响应对象
     * @param title     excel 名称
     * @param sheetName sheet 名称
     * @param clazz     实体类Class对象
     * @param list      数据集合
     * @Description 根据实体类注解导出excel
     **/
    public static void exportExcel(HttpServletResponse response, String title, String sheetName, Class clazz, List list) throws IOException {
        downloadSetting(response, title);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), clazz, list);
        workbook.write(response.getOutputStream());
    }

    /**
     * @param response  响应对象
     * @param clazz     实体类Class对象
     * @param list      数据集合
     * @param exportParams      参数
     * @Description 根据实体类注解导出excel
     **/
    public static void exportExcel(HttpServletResponse response, Class clazz, List list,ExportParams exportParams) throws IOException {
        downloadSetting(response, exportParams.getTitle());
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
        workbook.write(response.getOutputStream());
    }

    /**
     * @param response  响应对象
     * @param clazz     实体类Class对象
     * @param list      数据集合
     * @param exportParams      参数
     * @Description 根据实体类注解导出excel
     **/
    public static void tranferExcel(HttpServletResponse response, Class clazz, List list,ExportParams exportParams) throws IOException {
        transferSetting(response, exportParams.getTitle());
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
        workbook.write(response.getOutputStream());
    }


    /**
     * @param exportEntities 构建excel对象
     * @param data           导出数据
     * @param title          excel名称
     * @param sheetName      sheet名称
     * @Description 根据Map导出excel
     **/
    public static void exportExcel(HttpServletResponse response, List<ExcelExportEntity> exportEntities, List<Map<String, Object>> data, String title, String sheetName) throws IOException {
        downloadSetting(response, title);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), exportEntities, data);
        workbook.write(response.getOutputStream());
    }

    /**
     * @param response 响应对象
     * @Description 设置excel下载响应对象
     **/
    private static void downloadSetting(HttpServletResponse response, String title) throws UnsupportedEncodingException {
        title = title + ".xls";
        title = URLEncoder.encode(title, StandardCharsets.UTF_8.name());
        title = new String(title.getBytes(), StandardCharsets.ISO_8859_1.name());
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("Content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + title);
        //编码
        response.setCharacterEncoding("UTF-8");

    }

    /**
     * @param response 响应对象
     * @Description 设置excel传输响应对象
     **/
    private static void transferSetting(HttpServletResponse response, String title) throws UnsupportedEncodingException {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //编码
        response.setCharacterEncoding("UTF-8");

    }
}
